package com.code2roc.fastboot.framework.auth;

import com.code2roc.fastboot.framework.security.SecurityConfig;
import com.code2roc.fastboot.framework.util.ReflectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class TokenAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private SecurityConfig securityConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isvalid = false;

        //验证配置项
        List<String> anonymousAccessList = securityConfig.getAllowAnonymousAccess();
        String url = request.getRequestURL().toString();
        for (String item : anonymousAccessList) {
            if (item.endsWith("*")) {
                if (url.contains(item.replace("*", ""))) {
                    return true;
                }
            } else {
                if (url.endsWith(item)) {
                    return true;
                }
            }
        }
        //验证注解
        if (handler.getClass() == HandlerMethod.class) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (ReflectUtil.checkClassAnnotationPresent(handlerMethod.getBeanType(), AnonymousAccess.class)) {
                return true;
            }
            if (ReflectUtil.checkMethodAnnotationPresent(handlerMethod.getMethod(), AnonymousAccess.class)) {
                return true;
            }
        }

        String token = "";
        if (!isvalid) {
            token = request.getHeader("token");
            if (token == null || token.equals("null") || token.equals("")) {
                token = request.getParameter("token");// 手机端的上传图片控件无法设置header ，所以加上这句。
            }
            if (token == null || token.equals("null") || token.equals("")) {
                isvalid = false;
            } else {
                if (!tokenUtil.checkTokenValid(token)) {
                    isvalid = false;
                } else {
                    isvalid = true;
                }
            }
        }
        if (!isvalid) {
            response.sendRedirect(request.getContextPath() + "/frame/error/tokenAuthError");
        } else {
            tokenUtil.refreshToken(token);
        }
        return isvalid;
    }
}
